// pages/member/address.js
var util = require("../../utils/util.js");

//获取应用实例
const app = getApp()
var i;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: '',
        user: {},
        bindTel: false,  //绑定手机
        code: '',
        tel: '',
        yzmText: '发送验证码',
        yzmBtn: true,
        is_admin: 0,
        sign_in: 0,
        notice: '',
        logined: false,

        inviteQrCodeUrl: '',
        showQrcode: false,

        favourite_count: 0,
        
        member: {},

        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        ordercounts:{},
        issigned:false,
        sign_keep_days: 0,
        sign_days: 0,
        signrecords:0,
        isloading:true,
        showtip:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        let that = this;

        console.log("options->", options);

        if(options.hasOwnProperty('scene')) {
            let path = options.scene;
            console.log("path", path);
            let start = path.indexOf("invite");
            if(start >= 0) {
                let param = path.substring(start + 9, path.length);
                console.log("param", param);
                wx.setStorageSync('invite', param);
                app.globalData.invite = param;
            }
         
        }


        var date = new Date();
        let sign = wx.getStorageSync('sign');
        if(sign == date .getFullYear()+'-'+( date .getMonth() + 1)+'-'+date .getDate()) {
            that.setData({
                issigned: true
            })
        }



    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.checkLogin();
        this.loadData();
    },

    getCode(e) {
        let that = this;
        if(that.data.tel.trim().length != 11 ) {
            app.tip('请输入正确的手机格式');
            return ;
        }

        app.httpPost('member/send/code', {
            'mobile': that.data.tel,
        }, json => {
            if(json.data.error==0){
                that.doTime();
            }
        })


    },
    onSubmitTel(e) {
        let that = this;
        if(that.data.tel.trim().length != 11 || that.data.code.trim() == '') {
            app.tip('请填写完整');
            return ;
        }
        app.httpPost('member/wechat/bind', {
            'mobile': that.data.tel,
            'code': that.data.code,
            'openid': that.data.openid,
            'invite': app.globalData.invite || 0,
            'rawData': app.globalData.rawData,
        }, json => {
            if(json.data.error==0){
                that.setData({
                    bindTel: false,
                })
                app.tip("绑定成功");
            }
        })
    },

    doTime() {
        let that = this;
        var times = 60;
        i = setInterval(function() {
          times--;
          if (times <= 0) {
               that.setData({
                    yzmBtn: true,
                    yzmText: "发送验证码",
               })
               clearInterval(i);
          } else {
               that.setData({
                  yzmBtn: false,
                  yzmText: times + "s后重新获取"
               })
          }
        }, 1000);
    },


    hideModal(e) {
        this.setData({
            bindTel: false,
            showQrcode: false,
        })
    },

    getInputValue(e) {
        let that = this;
        let type = e.currentTarget.dataset.type;
        let value = e.detail.value;
        that.setData({
            [type]: value
        })
        
    },

    bindReturns(e) {
        if (e && e.detail && e.detail.rawData) {
            this.data.userinfo = e.detail.userInfo
            this.data.detail = e.detail

            this.doCallback()
        }
    },

    onLoading(e) {
        this.setData({
            isloading: true
        })
        this.loadData();
        
    },

    doCallback() {
        if (app.login) {
            //console.log(app.login)
            //app.login.isauthing = false

            wx.showLoading({
                title: '正在登录',
            })
            app.login.doLogin(success => {
                wx.hideLoading()
                app.success('登录成功')
                this.loadData();
                this.onLoading()
            })
        }
    },
    closethis(e){
        this.setData({
            showtip:false
        })
    },
    loadData(callback){
        let that = this;
        app.httpPost('member/personal', {
        }, json => {
            if(json.data.error==0){
                this.setData({
                    user: {
                        address: json.data.address,
                        identity: json.data.identity,
                        name: json.data.name,
                    },
                    
                    id: json.data.id,
                    sign_in: json.data.sign_in,
                    notice: json.data.notice,
                    is_admin: json.data.is_admin == 1 ? 1 : 0,
                })
            }
        })
    },
    onLoading(e) {
       /* this.setData({
            isloading:true
        })
        app.getProfile((profile) => {
            this.setData({
                member: profile
            })
            this.loadData()
        },true)
        */
        
    },
    checkLogin:function(){
        let that = this;
        console.log(app.globalData.authorization.access_token == null);
        console.log(app.globalData.authorization.access_token == '');
        if(app.globalData.authorization.access_token == '' || app.globalData.authorization.access_token == null) {
            app.error('您需要先登录！');
            console.log("-------");
            that.setData({
                showtip: true,
                logined: false,
            })
            return false;
        }else {
            that.setData({
                showtip: false,
                logined: true,
            })
          
            return true
        }
        
    },

    updateInfo(e) {
        if(this.checkLogin()) {
            wx.navigateTo({
                url: '/pages/member/form/form',
            })
        }
    },
    getCouponList: function (e) {
        if(this.checkLogin()) {
            wx.navigateTo({
                url: '/pages/member/coupon/coupon',
            })
        }
    },

    showInviteQrCode(e) {
        let that = this;
        app.httpPost('member/qcode', {
            'width': 200,
            'page': 'pages/member/index',
            'params': {
                invite: that.data.id,
            },
        }, json => {
            if(json.data.error==0){
                that.setData({
                    showQrcode: true,
                    inviteQrCodeUrl: app.globalData.imgDir+json.data.url
                })
            }
        })
    },

    onLogout(e) {

        let that = this;

        app.globalData.authorization = {};
        wx.removeStorage({
          key: 'login_token',
          success: function() {
              wx.redirectTo({
                url: '/pages/member/index',
              })
          }
        })
    },

    onSignIn(e) {
        let that = this;
        app.httpPost('member/sign_in', {
        }, json => {
            if(json.data.error==0){
                that.setData({
                    issigned: true,
                    sign_in: that.data.sign_in + 1
                })
                var date = new Date();
                wx.setStorageSync('sign',  date .getFullYear()+'-'+( date .getMonth() + 1)+'-'+date .getDate());
                app.tip('签到成功');
            }
        })
    },
    onModifyInfo(e) {

     
        if(this.checkLogin()) {
            wx.navigateTo({
                url: '/pages/member/modify/modify',
            })
        }

    },

    onScanQrCode() {
        let that = this;
        if(this.checkLogin() && that.data.is_admin == 1) {
            wx.scanCode({
                onlyFromCamera: true,
                success (res) {
                    // let path = 'pages/index/index?coupon_id=1';
                    let path = res.path;
                    console.log('-====->', res);
                    if(path != '') {
                        
                        let start = path.indexOf("coupon_id");
                        console.log('------->', start, res);
                        if(start > 0) {
                            let param = path.substring(start, path.length);
                            wx.redirectTo({
                            url: '/pages/member/form/form?' + param,
                            })
                        }else {
                            let start = path.indexOf("invite");
                            if(start > 0) {
                                let param = path.substring(start + 9, path.length);
                                console.log(param);
                                wx.setStorageSync('invite', param);
                                app.globalData.invite = param;
                            }
                            
                        }
                    }
              
                }
            })
        }
    },

    saveImg: function (e) {
        let that = this;
        wx.getImageInfo({
            src: that.data.inviteQrCodeUrl,
            success: function (res) {
                console.log(res);
                var path = res.path;
                wx.saveImageToPhotosAlbum({
                    filePath: path,
                    success: function (res) {
                        app.tip('图片已保存到相册');
                        that.hideModal();
                        // console.log('图片已保存到相册');
                    },
                    fail: function (res) {
                        console.log('保存失败');
                    }
                })
            }
        });
    },

    
    getCouponLogList: function(e) {
        if(this.checkLogin()) {
            wx.navigateTo({
                url: '/pages/member/use/use',
            })
        }

    },

    onTest: function(e) {
        wx.navigateTo({
          url: '/pages/member/form/form',
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },


})